package multithreaded;

public class SyncSample {
    class Printer {
        final Object lock = new Object();

        public void print1() throws InterruptedException {
            synchronized (lock) {
                Thread.sleep(500);
                System.out.print("只");
                Thread.sleep(500);
                System.out.print("因");
                Thread.sleep(500);
                System.out.print("你");
                Thread.sleep(500);
                System.out.print("太");
                Thread.sleep(500);
                System.out.println("美");
            }
        }

        public synchronized void print2() throws InterruptedException {
            Thread.sleep(500);
            System.out.print("只");
            Thread.sleep(500);
            System.out.print("因");
            Thread.sleep(500);
            System.out.print("你");
            Thread.sleep(500);
            System.out.print("太");
            Thread.sleep(500);
            System.out.println("美");
        }

    }

    class PrintTask implements Runnable {
        public Printer printer;

        @Override
        public void run() {
            try {
                printer.print2();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void start() throws InterruptedException {
        Printer printer = new Printer();
        for (int i = 0; i < 5; i++) {
            PrintTask task = new PrintTask();
            task.printer = printer;
            Thread thread = new Thread(task);
            thread.start();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SyncSample sample = new SyncSample();
        sample.start();
    }

}
